/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/record', 'N/search'], function (record, search) {

    function beforeSubmit(context) {
        //删除 相关总账影响记录
        if (context.type === 'delete') {
            var woId = context.oldRecord.getValue('createdfrom');
            var operationNumber = context.newRecord.getText('startoperation');
            var identify = context.oldRecord.getText('custbody_identify');
            var operationCharCode = String.fromCharCode(64 + parseInt(operationNumber));
            var identifyCharCode = String.fromCharCode(64 + parseInt(identify));
            var issueCode = 'X' + operationCharCode + identifyCharCode;
            //log.debug('issueCode1', issueCode);
            var fieldLookUp1 = search.lookupFields({
                type: 'workorder',
                id: woId,
                columns: ['custbody_gl_impact_record']
            });
            var oldGLImpact = fieldLookUp1.custbody_gl_impact_record;
            //log.debug('oldGLImpact', oldGLImpact);
            var strArray = oldGLImpact.split('|');
            //log.debug('strArray', strArray.toString());
            for (var index in strArray) {
                //log.debug('strArray[index]', strArray[index]);
                if (strArray[index].indexOf(issueCode) !== -1) {
                    strArray[index] = 'D';
                }
            }
            var newGLImpact = strArray.join('|');
            //log.debug('newGLImpact', newGLImpact);
            record.submitFields({
                type: 'workorder',
                id: woId,
                values: {
                    custbody_gl_impact_record: newGLImpact
                }
            });
        }

        //删除  相关工单工序详情  货品行,耗料数量
        if (context.type === 'delete') {
            var operationNumber = context.oldRecord.getText('startoperation');
            var woId = context.newRecord.getValue('createdfrom');
            var wo = record.load({type: 'workorder', id: woId, isDynamic: true});
            var assemblyItemId = wo.getValue('assemblyitem');
            var detailId;
            search.create({
                type: 'customrecord_workorder_process_detail',
                columns: [],
                filters: [['custrecord_workordernum', 'is', woId],
                    'and', ['custrecord_processnum', 'equalto', Number(operationNumber)],
                    'and', ['custrecord_assembly', 'is', assemblyItemId]]
            }).run().each(function (result) {
                detailId = result.id;
            });
            if (detailId) {//已完成数量 报工数量 次品数量 工序废品数量 成品废品数量
                var detailRec = record.load({
                    type: 'customrecord_workorder_process_detail',
                    id: detailId,
                    isDynamic: true
                });
                for (var i = 0; i < context.newRecord.getLineCount('component'); i++) {
                    if (operationNumber == context.newRecord.getSublistText('component', 'operationsequencenumber', i)) {
                        var itemId = context.newRecord.getSublistValue('component', 'item', i);
                        if (itemId !== '868' && itemId !== '49' && itemId !== '866') {
                            var line = detailRec.findSublistLineWithValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);
                            if (line !== -1) {
                                var issueQuantity = context.newRecord.getSublistValue('component', 'quantity', i);
                                var originIssueQty = detailRec.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', line);
                                //删除工单工序详情  货品行的耗料数量
                                detailRec.selectLine('recmachcustrecord_workorderprocess', line);
                                detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', originIssueQty - issueQuantity);//设置耗料数量
                                detailRec.commitLine('recmachcustrecord_workorderprocess');
                            }
                        }
                    }
                }


                detailRec.save();
            }
        }

        //修改  相关工单工序详情  货品行,耗料数量
        if (context.type === 'edit') {
            var operationNumber = context.oldRecord.getText('startoperation');
            var woId = context.newRecord.getValue('createdfrom');
            var wo = record.load({type: 'workorder', id: woId, isDynamic: true});
            var assemblyItemId = wo.getValue('assemblyitem');
            var detailId;
            search.create({
                type: 'customrecord_workorder_process_detail',
                columns: [],
                filters: [['custrecord_workordernum', 'is', woId],
                    'and', ['custrecord_processnum', 'equalto', Number(operationNumber)],
                    'and', ['custrecord_assembly', 'is', assemblyItemId]]
            }).run().each(function (result) {
                detailId = result.id;
            });
            if (detailId) {//已完成数量 报工数量 次品数量 工序废品数量 成品废品数量
                var detailRec = record.load({
                    type: 'customrecord_workorder_process_detail',
                    id: detailId,
                    isDynamic: true
                });
                for (var i = 0; i < context.newRecord.getLineCount('component'); i++) {
                    if (operationNumber == context.newRecord.getSublistText('component', 'operationsequencenumber', i)) {
                        var itemId = context.newRecord.getSublistValue('component', 'item', i);
                        if (itemId !== '868' && itemId !== '49' && itemId !== '866') {
                            var line = detailRec.findSublistLineWithValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);
                            if (line !== -1) {
                                var currIssueQuantity = context.newRecord.getSublistValue('component', 'quantity', i);
                                var oldIssueQuantity = context.oldRecord.getSublistValue('component', 'quantity', i);
                                var originIssueQty = detailRec.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', line);
                                //更新工单工序详情  货品行的耗料数量
                                detailRec.selectLine('recmachcustrecord_workorderprocess', line);
                                detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', originIssueQty + (currIssueQuantity - oldIssueQuantity));//设置耗料数量
                                detailRec.commitLine('recmachcustrecord_workorderprocess');
                            }
                        }
                    }
                }
                detailRec.save();
            }
        }
    }


    function afterSubmit(context) {
        if (context.type === 'delete' || context.type === 'edit') {
            return;
        }
        var woId = context.newRecord.getValue('createdfrom');
        var woRec = record.load({type: 'workorder', id: woId});
        var woUnits = woRec.getValue('units');
        var startoperationValue = context.newRecord.getValue('startoperation');
        var startoperationText = context.newRecord.getText('startoperation');
        var assembly = context.newRecord.getValue('item');
        var detailId;
        search.create({
            type: 'customrecord_workorder_process_detail',
            columns: [],
            filters: [['custrecord_workordernum', 'is', woId],
                'and', ['custrecord_processnum', 'equalto', Number(startoperationText)],
                'and', ['custrecord_assembly', 'is', assembly]]
        }).run().each(function (result) {
            detailId = result.id;
        });
        if (!detailId) { //不存在
            //创建工单工序详情
            var detailRec = record.create({type: 'customrecord_workorder_process_detail', isDynamic: true});
            detailRec.setValue('custrecord_workordernum', woId); // 工单号
            detailRec.setValue('custrecord_processnum', Number(startoperationText));//工序号
            detailRec.setValue('custrecord_assembly', assembly);//装配品
            detailRec.setValue('custrecord_externalprocess', startoperationValue);// 工序
            detailRec.setValue('custrecord_process_type', getProcessTypeIdByOperationTaskId(startoperationValue));//工序类型
            detailRec.setValue('custrecord_workunit', woUnits);//单位
            //创建工单工序详情明细行
            for (var i = 0; i < context.newRecord.getLineCount('component'); i++) {
                var processNum = context.newRecord.getText('startoperation');//工序号
                var operationsequencenumber = context.newRecord.getSublistValue('component', 'operationsequencenumber', i);//货品行工序号
                if (Number(processNum) === Number(operationsequencenumber)) {
                    var itemId = context.newRecord.getSublistValue('component', 'item', i);//货品
                    if (itemId !== '868' && itemId !== '49' && itemId !== '866') {//非委外加工费货品
                        var issueQuantity = context.newRecord.getSublistValue('component', 'quantity', i);
                        var itemUnits = context.newRecord.getSublistValue('component', 'units', i);
                        //创建工单工序详情明细行
                        detailRec.selectNewLine('recmachcustrecord_workorderprocess');
                        detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);//设置货品
                        detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', issueQuantity);//设置耗料数量
                        detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_unit', itemUnits);//设置单位
                        detailRec.commitLine('recmachcustrecord_workorderprocess');
                    }
                }
            }
            detailRec.save();
        } else if (detailId) {//存在工单工序详情,则更新(增加)货品明细行的耗料数量
            var detail = record.load({type: 'customrecord_workorder_process_detail', id: detailId, isDynamic: true});
            for (var i = 0; i < context.newRecord.getLineCount('component'); i++) {
                var a = context.newRecord.getText('startoperation');//工序号
                var b = context.newRecord.getSublistValue('component', 'operationsequencenumber', i);//货品行工序号
                if (Number(a) === Number(b)) {
                    var itemId = context.newRecord.getSublistValue('component', 'item', i);//货品
                    if (itemId !== '868' && itemId !== '49' && itemId !== '866') {//非委外加工费货品
                        var itemUnits = context.newRecord.getSublistValue('component', 'units', i);
                        var newIssueQty = context.newRecord.getSublistValue('component', 'quantity', i);
                        // var oldIssueQty = context.oldRecord.getSublistValue('component', 'quantity', i);

                        var lineNumber = detail.findSublistLineWithValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);
                        if (lineNumber !== -1) {//找到了需要更新的 工单工序明细行
                            var issueQty = detail.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', lineNumber);
                            detail.selectLine('recmachcustrecord_workorderprocess', lineNumber);
                            detail.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', issueQty + newIssueQty);
                            detail.commitLine('recmachcustrecord_workorderprocess');
                        } else {//没找到则 新建一行
                            //创建工单工序详情明细行
                            detail.selectNewLine('recmachcustrecord_workorderprocess');
                            detail.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);//设置货品
                            detail.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', newIssueQty);//设置耗料数量
                            detail.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_unit', itemUnits);//设置单位
                            detail.commitLine('recmachcustrecord_workorderprocess');
                        }
                    }
                }
            }
            detail.save();
        }
    }


    function getProcessTypeIdByOperationTaskId(operationTaskId) {
        var fieldLookUp1 = search.lookupFields({
            type: 'manufacturingoperationtask',
            id: operationTaskId,
            columns: ['manufacturingcosttemplate']
        });
        var manufacturingcosttemplateId = fieldLookUp1.manufacturingcosttemplate[0].value;
        var fieldLookUp2 = search.lookupFields({
            type: 'manufacturingcosttemplate',
            id: manufacturingcosttemplateId,
            columns: ['custrecord_processtype']
        });
        return fieldLookUp2.custrecord_processtype[0].value;
    }

    return {
        beforeSubmit: beforeSubmit,
        afterSubmit: afterSubmit
    };
});